﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;

namespace Controllers
{
    [OutputCache(Location = OutputCacheLocation.None)]
    public class RoleController : BaseController
    {
        public ActionResult Find(int start, int limit)
        {
            IQueryable<Role> list = from r in ctx.Roles orderby r.Id descending select r;
            CJson CJson = new CJson();
            string json = CJson.ToJsonString("totalCount:" + list.Count() + ",data", list.Skip(start).Take(limit).ToList());
            return Content(json);
        }

        public ActionResult Delete(int id)
        {
            var rdto = new ResultMessages();
            rdto.Message = "";
            Role list = ctx.Roles.Single(q => q.Id == id);
            try
            {
                ctx.Roles.DeleteOnSubmit(list);
                ctx.SubmitChanges();
                rdto.Message = "删除成功";
                rdto.Result = true;
            }
            catch (Exception ex)
            {
                rdto.Message = "删除失败";
                rdto.Result = false;
            }
            return Json(rdto);
        }

        public ActionResult AuthMenu(int roleId, string menuIds)
        {
            string retStr = "Succeed";
            IList<RoleMenus> authedList = ctx.RoleMenus.Where(r => r.RoleId == roleId).ToList();
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(menuIds))
            {
                string[] a = menuIds.Split(',');
                foreach (string s in a)
                {
                    if (!authedList.Where(r => r.MenuId == int.Parse(s)).Any())
                    {
                        sb.AppendFormat(@"insert into RoleMenus(RoleId,MenuId) values({0},{1});", roleId,s);
                    }
                }
            }
            foreach (RoleMenus rm in authedList)
            {
                if ((","+menuIds+",").IndexOf(","+rm.MenuId.ToString()+",") < 0)
                {
                    sb.AppendFormat(@"delete from RoleMenus where Id={0};",rm.Id);
                }
            }
            if (sb.Length != 0)
            {
                try
                {
                    ctx.ExecuteCommand(sb.ToString());
                }
                catch (Exception ex)
                {
                    retStr = ex.Message;
                }
            }
            return Json(retStr);
        }

        public ActionResult AuthDept(int roleId, string deptIds,string menu)
        {
            string retStr = "Succeed";
            IList<RoleControllerDept> authedList = ctx.RoleControllerDepts.Where(r => r.RoleId == roleId&&r.Controller==menu).ToList();
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(deptIds))
            {
                string[] a = deptIds.Split(',');
                foreach (string s in a)
                {
                    if (!authedList.Where(r => r.DeptId == int.Parse(s)).Any())
                    {
                        sb.AppendFormat(@"insert into RoleControllerDepts(RoleId,DeptId,Controller) values({0},{1},'{2}');", roleId, s,menu);
                    }
                }
            }
            foreach (RoleControllerDept r in authedList)
            {
                if (("," + deptIds + ",").IndexOf("," + r.DeptId.ToString() + ",") < 0)
                {
                    sb.AppendFormat(@"delete from RoleControllerDepts where Id={0};", r.Id);
                }
            }
            if (sb.Length != 0)
            {
                try
                {
                    ctx.ExecuteCommand(sb.ToString());
                }
                catch (Exception ex)
                {
                    retStr = ex.Message;
                }
            }
            return Json(retStr);
        }

        //按部门Id 和 职位Id 获取员工
        public ActionResult GetUnauthedEmp(int deptId, string posId)
        {
            IEnumerable<EmpBasicInfo> list;
            if (string.IsNullOrEmpty(posId))
            {
                string strSql = @"with t as(select Id,Text from Depts where Id={0}
  union all
  select a.Id,a.Text from Depts a,t where a.IsValid=1 and a.Pid=t.Id)
select Id,Name from(SELECT a.Id,Name,MIN(b.PosId)PosId FROM Employee a,EmpDepPositions b
  where LeaveDate is null
  and a.Id in(select EmpId from EmpDepPositions where DeptId in(select Id from t))
  and a.Id=b.EmpId group by a.Id,Name)t2 order by PosId,Id;";
                list = ctx.ExecuteQuery<EmpBasicInfo>(strSql, deptId);
            }
            else
            {
                string strSql = @"with t as(select Id,Text from Depts where Id={0}
  union all
  select a.Id,a.Text from Depts a,t where a.IsValid=1 and a.Pid=t.Id)
SELECT a.Id,Name FROM Employee a,EmpDepPositions b
  where LeaveDate is null
  and a.Id in(select EmpId from EmpDepPositions where DeptId in(select Id from t))
  and a.Id=b.EmpId and b.PosId={1} order by b.PosId,a.Id;";
                list = ctx.ExecuteQuery<EmpBasicInfo>(strSql, deptId, int.Parse(posId));
            }
            return Json(list);
        }

        public ActionResult AuthEmp(int roleId, string empIds)
        {
            string retStr = "Succeed";
            IList<EmpRole> authedList = ctx.EmpRoles.Where(r => r.RoleId == roleId).ToList();
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(empIds))
            {
                string[] a = empIds.Split(',');
                foreach (string s in a)
                {
                    if (!authedList.Where(r => r.EmpId == int.Parse(s)).Any())
                    {
                        sb.AppendFormat(@"insert into EmpRoles(RoleId,EmpId) values({0},{1});", roleId, s);
                    }
                }
            }
            foreach (EmpRole v in authedList)
            {
                if (("," + empIds + ",").IndexOf("," + v.EmpId.ToString() + ",") < 0)
                {
                    sb.AppendFormat(@"delete from EmpRoles where Id={0};", v.Id);
                }
            }
            if (sb.Length != 0)
            {
                try
                {
                    ctx.ExecuteCommand(sb.ToString());
                }
                catch (Exception ex)
                {
                    retStr = ex.Message;
                }
            }
            return Json(retStr);
        }
    }
}